package com.j180.spring_jwt_demo.controller;

import com.j180.spring_jwt_demo.bean.ResultBean;
import com.j180.spring_jwt_demo.bean.UserBean;
import com.j180.spring_jwt_demo.service.IUserService;
import com.j180.spring_jwt_demo.util.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Api("用户控制器")
@RestController
@RequestMapping("/user")
public class UserController  {
    @Resource
    private IUserService iUserService;

    @ApiOperation("登录方法")
    @GetMapping ("/login/{username}/{pwd}")
    public ResultBean login(@ApiParam(value = "用户名",required = true)
                               @PathVariable("username") String username,
                            @ApiParam(value = "密码",required = true)
                            @PathVariable("pwd") String pwd){
        ResultBean resultBean = new ResultBean();

        UserBean userBean = iUserService.login(username, pwd);

        if(userBean!=null){

            Map<String,String> map = new HashMap<>();
            map.put("userId",userBean.getId()+"");
            map.put("userName",userBean.getUserName()+"");
            map.put("date", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            //创建一个token
            String token = JWTUtil.getToken(map,3);
            resultBean.setCode(0);
            resultBean.setMsg("登录成功");
            resultBean.setDatas(token);

        }else{
            resultBean.setCode(2);
            resultBean.setMsg("登录失败");
        }
       return resultBean;
    }
}
